<?php
namespace Method;

class PageData
{
    public $recordPrePage = 12;
    public $currentPage = 1;
    public $countQuery;
    public $context = array();

    /**
     * create a new PageDate object
     * */
    public function __construct($tableName, $extras = '')
    {
        global $pdo;
        $sql = 'SELECT COUNT(*) FROM `' . $tableName . '` ' . $extras;
        $this->countQuery = $pdo->prepare("{$sql}");

        if ($_POST['page']) {
            $this->setPage($_POST('page'));
        }
    }

    public function setPage($currentPage)
    {
        $this->currentPage = max(1, intval($currentPage));
    }

    public function setRecordPrePage($recordPrePage)
    {
        $this->recordPrePage = $recordPrePage;
    }

    public function execute()
    {
        $this->countQuery->execute();
        $totalRecord = $this->countQuery->fetchColumn();//微博总数
        $totalPage = max(ceil($totalRecord / $this->recordPrePage), 1);//总页数
        $this->currentPage = min($this->currentPage, $totalPage);//当前页数
        $pageDataStart = ($this->currentPage - 1) * $this->recordPrePage;//数据库开始条数

        return $this->context = array(
            'num' => $totalRecord,
            'totalPage' => $totalPage,
            'currentPage' => $this->currentPage,
            'pageSize' => $this->recordPrePage,
            'DataStart' => $pageDataStart
        );
    }

    public function getContext()
    {
        return $this->context;
    }

}